//
//  FJPopularPushViewController.swift
//  FruitJuice
//
//  Created by Rui on 2024/1/7.
//

import UIKit

class FJPopularPushViewController: FJBaseViewController {

    private let backButton = c_make_ex(UIButton.self)
        .image("FJ_Profile_back").end()
    private lazy var tableView: UITableView = {
        let tableView = UITableView()
        tableView.backgroundColor = .clear
        tableView.tableFooterView = UIView(frame: .zero)
        tableView.separatorStyle = .none
        tableView.delegate = self
        tableView.dataSource = self
        tableView.register(FJPicTableViewCell.self,FJContentTableViewCell.self)

        return tableView
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()

        view.subviews{
            backButton
            tableView
        }
        
        backButton.top(.statusHeight + 7).leading(15).size(30)
        tableView.leading(0).trailing(0).bottom(0).top(.navi_height)
        
        backButton.addTarget(self, action: #selector(clickBackButton), for: .touchUpInside)
    }
    
    @objc private func clickBackButton(){
        self.navigationController?.popViewController(animated: true)
    }
}

extension FJPopularPushViewController: UITableViewDelegate,UITableViewDataSource{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 2
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        if indexPath.row == 0 {
            let cell = tableView.cell(FJPicTableViewCell.self, indexPath: indexPath)
            cell.picClosure = {
                
            }
//            cell.delClosure = {
//                
//            }
            return cell
        }else{
            let cell = tableView.cell(FJContentTableViewCell.self, indexPath: indexPath)
            return cell
        }
    }

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        
        if indexPath.row == 0 {
            
            return 215
        }else{
            
            return 200
        }
    }
}

class FJPicTableViewCell: UITableViewCell, UICollectionViewDelegate, UICollectionViewDataSource {

    private let titleLabel          = c_make_ex(UILabel.self)
        .font(19.font_semiBold).text("Your science pictures：")
        .color(.black).end()
    private let collectionView = UICollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout())
    var dataSource: [FJPushPicModel] = [FJPushPicModel(url: "",id: 0)] {
        didSet{
            collectionView.reloadData()
        }
    }
    var picClosure: (() -> Void)?
    var delClosure: ((_ id: Int) -> Void)?
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        selectionStyle = .none
        backgroundColor = .clear
        contentView.backgroundColor = .clear

        contentView.subviews{
            titleLabel
            collectionView
        }
        
        titleLabel.leading(15).top(0)
        collectionView.leading(0).trailing(0).bottom(15)
        collectionView.Top == titleLabel.Bottom + 15
        let layout = UICollectionViewFlowLayout()
        layout.scrollDirection = .horizontal
        layout.minimumLineSpacing = 10
        layout.minimumInteritemSpacing = 10
        layout.itemSize = CGSize(width: 130.0, height: 155.0)
        layout.sectionInset = UIEdgeInsets(top: 0, left: 15.0, bottom: 0, right: 0)
        collectionView.style { v in
            v.collectionViewLayout = layout
            v.backgroundColor = .clear
            v.register(FJPushPicItemCell.self, forCellWithReuseIdentifier: FJPushPicItemCell.description())
            v.showsVerticalScrollIndicator = false
            v.delegate = self
            v.dataSource = self
        }

    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        dataSource.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        guard let item = collectionView.dequeueReusableCell(withReuseIdentifier: FJPushPicItemCell.description(), for: indexPath) as? FJPushPicItemCell else { return UICollectionViewCell() }
        var model = dataSource[indexPath.row]
        model.id = indexPath.row + 1000
        item.model = model
        item.delClosure = { itemId in
            if itemId == 1000 {
                return
            }
            self.dataSource.removeAll(where: {$0.id == itemId})
            let delIndex = itemId - 1001
            self.delClosure?(delIndex)
        }
        return item
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        picClosure?()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }

}


class FJContentTableViewCell: UITableViewCell, UITextViewDelegate {

    private let titleLabel          = c_make_ex(UILabel.self)
        .font(19.font_semiBold).text("Your popular science content：")
        .color(.black).end()
    private let notesTextView       = c_make_ex(UITextView.self)
        .bgColor("#EFEFEF").corner(12.5).placeholder("Popular science content must be true")
        .color(.black).font(16.font_medium)
        .placeholderColor("#B5B5B5").placeholderInsets(UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10))
        .placeholderFont(16.font_medium).end()
    private let numberLabel         = c_make_ex(UILabel.self)
        .font(14.font_regular).text("0/2000")
        .color("#B5B5B5").alignment(.right).end()
    
    var noteClosure: ((_ text: String) -> Void)?
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        selectionStyle = .none
        backgroundColor = .clear
        contentView.backgroundColor = .clear

        contentView.subviews{
            titleLabel
            notesTextView.subviews{
                numberLabel
            }
        }
        
        titleLabel.leading(15).top(0)
        notesTextView.leading(15).trailing(15).height(130)
        notesTextView.Top == titleLabel.Bottom + 15.0
        numberLabel.bottom(15).trailing(15)
        
        notesTextView.style { v in
            v.contentInset = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
        }
        notesTextView.delegate = self
    }
    
    func textViewDidChange(_ textView: UITextView) {
        // 更新文字数量标签
        let characterCount = textView.text.count
        numberLabel.text = "\(characterCount)/2000"
        noteClosure?(textView.text)
    }
    
    func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
        // 获取当前文本总长度
        let currentText = textView.text as NSString
        let newText = currentText.replacingCharacters(in: range, with: text)

        // 设置最大字符数限制
        let maxCharacterCount = 2000

        // 检查是否超过最大字符数
        return newText.count <= maxCharacterCount
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }

}
